import Vue from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";

// 引入element-UI组件和样式
import ElementUI from "element-ui";
import "element-ui/lib/theme-chalk/index.css";

import 'font-awesome/css/font-awesome.css'

Vue.use(ElementUI);

// 引入四个请求对象
import { getRequest } from "./utils/api";
import { postRequest } from "./utils/api";
import { putRequest } from "./utils/api";
import { deleteRequest } from "./utils/api";

import { initMenu } from "./utils/menu";

// 将请求放入Vue原型中
Vue.prototype.getRequest = getRequest;
Vue.prototype.postRequest = postRequest;
Vue.prototype.putRequest = putRequest;
Vue.prototype.deleteRequest = deleteRequest;

// 前置守卫
router.beforeEach((to, from, next) => {
    // 判断是否登录
    if (window.sessionStorage.getItem("token")) {
        // 初始化菜单
        initMenu(router, store);
        // 判断用户信息是否存在
        if (!window.sessionStorage.getItem('user')){
            return getRequest('/admin/info').then(res => {
                if(res){
                    window.sessionStorage.setItem('user', JSON.stringify(res))
                    next()
                }
            })
        }
        next();
    } else {
        // 未登录
        // 判断是否访问的是登录页
        if (to.path == "/") {
            // 直接放行
            next();
        } else {
            // 如果不是登录页，则重定向为
            next("/?redirect=" + to.path);
        }
    }
});

// 生产模式的提示
Vue.config.productionTip = false;

new Vue({
    router,
    store,
    render: (h) => h(App),
}).$mount("#app");
